import config from "@/config"
let loginLock = false;

export default {
  service(url, data = {}, method = 'POST', callback, failCallback) {
    // 异步请求数据
    return new Promise((resolve) => {
      let accessToken = uni.getStorageSync("token");
      const baseUrl = config.baseUrl;
      uni.request({
        url: baseUrl + url,
        data: data,
        method: method,
        header: {
          "Content-Type": "application/json",
          "token": accessToken,
        },
        /**
         * @param {{ code }} res.data
         * @param {{ statusCode }} res
         */
        success: (res) => {
          if (res.statusCode === 200) {
            if (res.data.code === 200) {
              resolve(res.data);
              if (callback) {
                uni.showToast({
                  title: res.data.msg,
                  icon: "none",
                });
              }
            } else if (res.data.code === 401) {
              if (failCallback) {
                failCallback(res.data);
              }
              if (!loginLock) {
                loginLock = true;
                uni.showModal({
                  title: "登录提示",
                  content: "您尚未登录，或登录已过期，请您重新登录。",
                  showCancel: true,
                  confirmText: "登录",
                  success: (_) => {
                    uni.setStorageSync("token", "");
                    uni.navigateTo({
                      url: "/pages/login/login",
                    });
                  },
                  complete: () => {
                    loginLock = false;
                  },
                });
              }
            } else {
              if (failCallback) {
                failCallback(res.data);
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: "none",
                });
              }
            }
          }
        },
      });
    }).catch((_) => {
    })
  },
  get(url, data = {}, failCallback) {
    return this.service(url, data, "get", failCallback)
  },
  post(url, data = {}, callback, failCallback) {
    return this.service(url, data, "post", failCallback)
  }
}